<template>
  <div id="recommend-view" style="padding: 10px; padding-bottom: 80px; background-color: #F6F7F9; height: 100%;">
    <!-- 轮播图 -->
    <van-swipe :autoplay="3000" style="margin-top: 10px; margin-bottom: 20px;">
      <van-swipe-item v-for="(image, index) in images" :key="index">
        <div class="card">
          <img style="height:300px;width: 100%" v-lazy="require(`@/${image}`)" />
        </div>
      </van-swipe-item>
    </van-swipe>

    <!-- 分类列表 -->
    <div class="card">
      <van-grid :border="true" :column-num="3">
        <van-grid-item @click="updateActive(1)" icon-size="35px" :icon="require('@/assets/icons/category_cat.svg')"
                       text="猫咪">
        </van-grid-item>
        <van-grid-item @click="updateActive(2)" icon-size="35px" :icon="require('@/assets/icons/category_dog.svg')"
                       text="狗狗">
        </van-grid-item>
        <van-grid-item @click="updateActive(3)" icon-size="35px" :icon="require('@/assets/icons/category_more.svg')"
                       text="周边">
        </van-grid-item>
      </van-grid>
    </div>

    <!-- 商品展示 -->
    <product-card-row
        :products="products"
        @product-click="handleProductClick"
        style="margin-top: 20px;">
    </product-card-row>
  </div>
</template>

<script>
import { Swipe as VanSwipe, SwipeItem as VanSwipeItem } from 'vant';
import { Grid as VanGrid, GridItem as VanGridItem } from 'vant';

import ProductCardRow from '@/components/ProductCardRow.vue';
import http from '@/plugins/http'

export default {
  name: "recommend-view",
  components: {
    VanSwipe,
    VanSwipeItem,
    VanGrid,
    VanGridItem,
    ProductCardRow
  },
  mounted(){
    this.loadPage();
  },
  data() {
    return {
      images: [
        'assets/cat/xianluo.png',
        'assets/dog/labuladuo.png',
      ],
      products: []
    }
  },
  methods: {
    loadPage(){
      http.get('/product/all-sorted').then(res=>{
        if(res.statusCode==='200')
        {
          console.log(res.data)
          this.products = res.data;
        }
      })
    },
    updateActive(page_number) {
      this.$emit('updateActive', page_number);
    },
    handleProductClick(productId) {
      http.post(`/product/increment-click/${productId}`).then(res => {
        if (res.statusCode === '200' && res.data) {
          // 更新被点击的产品的点击次数
          const productIndex = this.products.findIndex(p => p.productId === productId);
          if (productIndex !== -1) {
            // 使用 Vue.set 来确保响应性更新
            this.$set(this.products, productIndex, { ...this.products[productIndex], click: res.data.click });
          }
          // 重新排序产品列表
          this.products.sort((a, b) => b.click - a.click);
        }
      }).catch(error => {
        console.error("增加点击次数失败:", error);
      });
    }
  }
}
</script>

<style scoped>
.card {
  border-radius: 15px;
  overflow: hidden;
}
</style>